package com.unis.controller.system;

import com.alibaba.fastjson.JSON;
import com.unis.common.excel.ExportBeanExcel;
import com.unis.common.exception.http.RequestEntityTooLargeException;
import com.unis.common.util.ResponseUtil;
import com.unis.common.util.ValidateUtil;
import com.unis.controller.BaseController;
import com.unis.dto.ResultDto;
import com.unis.logger.TargetLogger;
import com.unis.model.system.Menu;
import com.unis.service.system.MenuService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2019/1/8/008.
 */
@Controller
@RequestMapping("/system/menu")
public class MenuController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(MenuController.class);
    @Autowired
    private MenuService menuService;


    @RequestMapping(value = "/levelList", method = RequestMethod.POST)
    @ResponseBody
    public void queryLevelMenu(String parentCode,int codeLevel,HttpServletResponse response) throws Exception {
        if (codeLevel<1){
            codeLevel = 1;
        }
        String json = JSON.toJSONString(menuService.queryMenuByParm(menuService.getUserInfo().getPk(),codeLevel,parentCode));
        ResponseUtil.outJson(response,json);
    }

    @RequestMapping(value = "/sscd")
    @ResponseBody
    public List sscd(String cdmc) throws Exception {
        List list = null;
        Map<String,Object> map = new HashMap<>();
        if (cdmc!=null&&!"".equals(cdmc)){
            Example example = new Example(Menu.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andLike("name","%"+cdmc+"%");
            criteria.andEqualTo("isparent",0);
            criteria.andEqualTo("yxx",1);
            List<Menu> cds = menuService.queryListByExample(example);
            if (cds.size()>0){
                list = new ArrayList();
                for (Menu menu:cds) {
                    map = new HashMap<>();
                    map.put("pageId",menu.getPageId());
                    map.put("ul",menu.getUrl());
                    map.put("icon",menu.getIcon());
                    map.put("name",menu.getName());
                    list.add(map);
                }
            }
        }
        return list;
    }

    @RequiresPermissions("SYS_MENU")
    @RequestMapping("/page")
    public String forwordPage()  {
        return "system/menu/menuPage";
    }

    @TargetLogger("040401")
    @RequiresPermissions("SYS_MENU")
    @RequestMapping( "/list")
    @ResponseBody
    public ResultDto queryMenuList(@RequestParam Map<?, ?> paramMap){
        int pageSize = paramMap.get("pageSize")==null ? 10 : Integer.parseInt(paramMap.get("pageSize").toString());
        int pageNumber = paramMap.get("pageNumber")==null ? 1 : Integer.parseInt(paramMap.get("pageNumber").toString());
        try {
            ResultDto page = menuService.queryListByPage(paramMap,pageNumber,pageSize);
            return page;
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new RequestEntityTooLargeException(e.getMessage());
        }
    }
    @TargetLogger("040402")
    @RequiresPermissions("SYS_MENU")
    @RequestMapping("/excel")
    public void exportMenuList(HttpServletResponse response,@RequestParam Map<?, ?> paramMap){
        //导出默认1000行
        int pageSize = EXPORT_SIZE;
        int pageNumber = 1;
        OutputStream os = null;
        try {
            ResultDto page = menuService.queryListByPage(paramMap,pageNumber,pageSize);
            List list = page.getRows();

            response.setContentType("application/vnd.ms-excel");
            response.addHeader("Content-Disposition", "attachment;filename=exportMenu"+ System.currentTimeMillis() + ".xls");
            os = response.getOutputStream();

            ExportBeanExcel<Menu> export = new ExportBeanExcel<Menu>();
            //根据需求选择导出字段，注意数据库中带有_等字符字段修改
            //导出表头
            String[] headers = {"菜单代码","菜单名称","是否包含子菜单","URL路径","上级菜单","菜单级别","菜单描述"};
            //对应字段 headers 与cols一一对应
            String[] cols = {"code","name","isparent","url","parentCode","codeLevel","comments"};

            export.exportExcel("系统菜单",headers,cols,list,os);

            os.flush();
            os.close();
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new RequestEntityTooLargeException(e.getMessage());
        }
    }

    @TargetLogger("0401")
    @RequiresPermissions("SYS_MENU")
    @RequestMapping("/curd")
    @ResponseBody
    public Map<String,String> curd(String curdType,Menu menu) throws Exception {
        Map<String,String> resultMap = new HashMap<>();
        String msg = null;
        if (menu!=null){
            if (StringUtils.equalsIgnoreCase(curdType,"insert")){
                //valid校验需在Menu的字段上增加校验规则，规则与表单规则保持一致
                msg = ValidateUtil.valid(menu);
                if (StringUtils.isNotBlank(msg)){
                    logger.error("valid insert Menu is error :"+msg);
                    resultMap.put("msg",msg);
                    return resultMap;
                }
                menuService.insert(menu);
            }else if (StringUtils.equalsIgnoreCase(curdType,"delete")){
                if(StringUtils.isNotBlank(menu.getPk())) {
                    menuService.delete(menu.getPk()); //主键删除
                }else {
                    msg="没有要删除的数据";
                    logger.error("valid delete Menu is error :"+msg);
                    resultMap.put("msg",msg);
                    return resultMap;
                }
            }else if (StringUtils.equalsIgnoreCase(curdType,"update")){
                msg = ValidateUtil.valid(menu);
                if (StringUtils.isNotBlank(msg)){
                    logger.error("valid update Menu is error :"+msg);
                    resultMap.put("msg",msg);
                    return resultMap;
                }
                menuService.updateByPrimaryKey(menu);
            }
            msg = "操作成功";
        }else{
            msg="信息未填写";
            logger.error(msg);
        }
        resultMap.put("msg",msg);
        return resultMap;
    }

}
